package com.nativetalk.service.found.update;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.FoundChange.TdNtMembFoundChangeInset;
import com.nativetalk.bean.member.TdNtMemberInvite;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.dao.TdNtLiveStudyDao;
import com.nativetalk.dao.TdNtMembFoundChangeDao;
import com.nativetalk.dao.TdNtMembSetmealDao;
import com.nativetalk.dao.TdNtMemberDao;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

/**
 * Created by lizhun on 16/1/6.
 */
@Service
public class FoundChangeUpdateServiceImpl implements FoundChangeUpdateService {
    private static Logger logger = Logger.getLogger(FoundChangeUpdateServiceImpl.class);
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TdNtMembFoundChangeDao tdNtMembFoundChangeDao;
    @Resource
    private TdNtLiveStudyDao tdNtLiveStudyDao;
    @Resource
    private TdNtMembSetmealDao tdNtMembSetmealDao;

    @Override
    public RetInfo notify(Map<String, Object> paymentInfo) {
        String logInfo = this.getClass().getName() + ":notify:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            boolean isPaid = (Boolean) paymentInfo.get("paid");                        //是否已经付款
            String orderNo = paymentInfo.get("order_no").toString();                   //支付编号
            int amount = Integer.valueOf(paymentInfo.get("amount").toString()) / 100;  //付款金额，单位：元

            //ping++ Webhooks 回调测试订单编号123456789
            if ("123456789".equals(orderNo)) {
                return retInfo;
            }

            TdNtMembFoundChangeInset tdNtMembFoundChange = tdNtMembFoundChangeDao.findTdNtMembFoundChangeByOrderNo(orderNo);
            //如果支付记录不存在，新增一条支付记录
            if (tdNtMembFoundChange == null) {
                TdNtMembFoundChangeInset tdNtMembFoundChangeInset = new TdNtMembFoundChangeInset();
                tdNtMembFoundChangeInset.setMfchg_number(orderNo);
                tdNtMembFoundChangeInset.setMfchg_change_amount(new BigDecimal(amount));
                tdNtMembFoundChangeInset.setMfchg_change_time(new Timestamp(new Date().getTime()));
                tdNtMembFoundChangeInset.setState(isPaid ? Constants.PayState.success : Constants.PayState.failure);
                tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeInset);

            } else {//如果支付记录已经存在，更新支付状态为成功
                //付款成功
                if (isPaid) {
                    tdNtMembFoundChangeDao.updatePaymentState(orderNo, Constants.PayState.success);
                    //更新相关业务表
                    //1. 购买课程，更新套餐中的支付状态
                    if (tdNtMembFoundChange.getType().intValue() == Constants.ChargeType.buy_course_code) {
                        tdNtMembSetmealDao.updatePaymentStateByMfchgId(tdNtMembFoundChange.getMfchg_id(), Constants.SetMealPayState.paid);
                    }

                    //2. 购买公开课
                    if (tdNtMembFoundChange.getType().intValue() == Constants.ChargeType.buy_live_course_code) {
                        tdNtLiveStudyDao.updatePaymentStateByMfchgId(tdNtMembFoundChange.getMfchg_id(), Constants.PayState.success);
                    }

                } else {//付款失败
                    if (tdNtMembFoundChange.getState().equals(Constants.PayState.success)) {
                        //资金变化记录更新为：支付失败
                        tdNtMembFoundChangeDao.updatePaymentState(orderNo, Constants.PayState.failure);

                        //资金变化类型为支付
                        //扣除余额（应为原来的充值记录为成功，说明原来的余额已经充值成功，然而Ping++回调接口说付款失败，因此这时需要把原先添加余额里的钱在扣除掉）
                        if (tdNtMembFoundChange.getType().intValue() == Constants.ChargeType.recharge_code) {
                            TdNtMemberInvite tdNtMemberInvite = new TdNtMemberInvite();
                            tdNtMemberInvite.setMemb_id(tdNtMembFoundChange.getMemb_id());
                            BigDecimal amount_bigdecimal = new BigDecimal(amount);
                            BigDecimal balanceFront = tdNtMemberInvite.getMemb_balance();//变化前的金额
                            BigDecimal balanceBack = balanceFront.subtract(amount_bigdecimal);//变化后的金额
                            tdNtMemberInvite.setMemb_balance(balanceBack);
                            tdNtMemberDao.updateTdNtMemberBalance(tdNtMemberInvite);

                            //添加一条资金变化记录(扣除余额)
                            TdNtMembFoundChangeInset tdNtMembFoundChangeNew = copy(tdNtMembFoundChange);
                            tdNtMembFoundChangeNew.setMfchg_front_amount(balanceFront);
                            tdNtMembFoundChangeNew.setMfchg_back_amount(balanceBack);
                            tdNtMembFoundChangeDao.insertTdNtMembFoundChange(tdNtMembFoundChangeNew);
                        }
                    }

                    //更新相关业务表
                    //1. 购买课程，更新套餐中的支付状态
                    if (tdNtMembFoundChange.getType().intValue() == Constants.ChargeType.buy_course_code) {
                        tdNtMembSetmealDao.updatePaymentStateByMfchgId(tdNtMembFoundChange.getMfchg_id(), Constants.SetMealPayState.un_end);
                    }

                    //2. 购买公开课
                    if (tdNtMembFoundChange.getType().intValue() == Constants.ChargeType.buy_live_course_code) {
                        tdNtLiveStudyDao.updatePaymentStateByMfchgId(tdNtMembFoundChange.getMfchg_id(), Constants.PayState.failure);
                    }

                }


            }


        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }


    private TdNtMembFoundChangeInset copy(TdNtMembFoundChangeInset old) {
        TdNtMembFoundChangeInset newObj = new TdNtMembFoundChangeInset();
        newObj.setMfchg_change_time(new Timestamp(new Date().getTime()));
        newObj.setState(Constants.PayState.success);
        newObj.setMfchg_change_amount(old.getMfchg_change_amount());
        newObj.setMfchg_number(old.getMfchg_number());
        newObj.setMemb_id(old.getMemb_id());
        newObj.setMfchg_change_month(CommonUtil.getMonth(new Date()));
        newObj.setMfchg_change_name(Constants.ChargeType.recharge_failure_msg);
        newObj.setType(Constants.ChargeType.recharge_failure_code);
        newObj.setMfchg_change_type(Constants.FundChangeType.wallet_out);
        newObj.setMoney_change_type(Constants.PaymentChannel.wallet);
        return newObj;
    }

}
